<style scoped lang="less">
.areatree {
  border: 1px solid #595959;
  height: 1rem;
  overflow: hidden;
  .area-tree {
    height: 100% !important;
    padding: 0 !important;
  }
}
</style>
<template>
  <div class="area-tree">
    <el-tree
      :data="data"
      node-key="id"
      :props="defaultProps"
      @node-click="handleNodeClick"
      unselectable="on"
      :expand-on-click-node="false"
      :default-expanded-keys="defaultExpandedKeys"
      :indent="36"
      @node-contextmenu="showContextMenu"
    >
      <div
        class="tree-node"
        :class="{ active: activeNodeId == node.id }"
        slot-scope="{ node, data }"
      >
        {{ data.name }}
      </div>
    </el-tree>

    <ul
      class="context-menu"
      v-if="menuVisible"
      :style="{ left: menuX + 'px', top: menuY + 'px' }"
    >
      <li
        v-for="(item, index) in menuList"
        :key="index"
        @click="menuHandler(item.handler)"
      >
        <span>{{ item.name }}</span>
      </li>
    </ul>
    <!-- 添加/编辑 start -->
    <el-dialog
      :title="newModalTitle"
      :visible.sync="newModalVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
    >
      <el-form ref="newForm" :model="newForm" label-width="120px">
        <el-form-item label="所属机构：" v-if="newForm.pid">
          {{ activeOrgNames.join("-") }}
        </el-form-item>
        <el-form-item
          label="部门名称："
          prop="name"
          :rules="[
            { required: true, message: '请输入部门名称', trigger: 'change' },
          ]"
        >
          <el-input
            placeholder="请输入"
            type="text"
            v-model.trim="newForm.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="行政区划：">
          <div v-if="regionName" @click="regionName = null">
            {{ regionName }}（点击选择）
          </div>
          <div class="areatree" v-else>
            <areaTree
              type="all"
              :isEditable="true"
              @nodeClick="areaClickAction"
            ></areaTree>
          </div>
        </el-form-item>
        <el-form-item label="部门描述：" prop="des">
          <el-input
            placeholder="请输入"
            type="textarea"
            v-model.trim="newForm.des"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="cancel" @click="newModalVisible = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          :loading="adding"
          @click="submitAction"
          :disabled="!$store.getters.hasEditPermission"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 添加/编辑 end -->
    <!-- 授权 start -->
    <el-dialog
      :title="authModalTitle"
      :visible.sync="authModalVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
    >
      <el-form ref="authForm" :model="authForm" label-width="120px">
        <el-form-item label="授权机构：">
          {{ activeOrgNames.join("-") }}
        </el-form-item>
        <el-form-item
          label="被授权机构："
          prop="authorizedOrgId"
          :rules="[
            { required: true, message: '请选择被授权机构', trigger: 'change' },
          ]"
        >
          <div class="flex">
            <div class="flex-1 mr-10">
              <el-input
                placeholder="请选择"
                type="text"
                v-model.trim="authOrg.name"
                readonly
              ></el-input>
            </div>
            <div>
              <el-button type="green" @click="chooseOrg">选择机构</el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="cancel" @click="authModalVisible = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          :loading="adding"
          @click="submitAuthAction"
          :disabled="!$store.getters.hasEditPermission"
          >确定</el-button
        >
      </div>
    </el-dialog>
    <!-- 授权 end -->
    <!-- 授权机构列表 start -->
    <el-dialog
      title="机构列表"
      :visible.sync="authOrgsVisible"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
    >
      <el-table
        :data="orgList"
        class="mt-10"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="des" label="描述"></el-table-column>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <div class="nowrap">
              <el-button type="primary" @click="selectOrg(scope.row)">
                选择
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
  <!-- render-content="renderContent" -->
</template>
<script>
import { mapState } from "vuex";
import areaTree from "@/components/census/AreaTree.vue";

export default {
  name: "iotBlk",
  components: {
    areaTree,
  },
  props: {
    ContextMenu: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
      default: "",
    },
    moreType: {
      type: Number,
      default: 0,
    },
    size: {
      type: String,
      default: "small",
    },
    isAdmin: {
      type: Boolean,
      default: true,
    },
  },
  computed: {
    ...mapState(["scale"]),
    defaultExpandedKeys() {
      if (this.data.length > 0) {
        let ids = [];
        let provs = this.isAdmin ? this.data[0].orgs : this.data[0].list;
        let citys = [];
        provs.forEach((item, index) => {
          citys = this.isAdmin
            ? [...citys, ...item.orgs]
            : [...citys, ...item.list];
        });
        ids = citys.map((item) => item.id);
        return [this.data[0].id];
      }
      return [];
    },
    activeOrgNames() {
      if (!this.activeNode) {
        return [];
      }
      let orgNames = [this.activeNode.data.name];
      // this.getAllName(this.activeNode,orgNames)
      // orgNames = orgNames.reverse()
      return orgNames;
    },
    defaultProps() {
      if (this.isAdmin) {
        return {
          children: "orgs",
          label: "name",
        };
      }
      return {
        children: "list",
        label: "name",
      };
    },
  },
  watch: {},
  data() {
    return {
      data: [],
      activeNodeId: "",
      activeNode: null,
      activeData: null,
      // activeOrgNames:[],
      menuList: [
        {
          name: "新建子部门",
          handler: "new",
        },
        {
          name: "编辑",
          handler: "edit",
        },
        {
          name: "删除",
          handler: "delete",
        },
      ],
      menuVisible: false,
      menuX: 0,
      menuY: 0,
      newModalTitle: "新建部门",
      newModalVisible: false,
      newForm: {},
      adding: false,
      authModalTitle: "",
      authModalVisible: false,
      authForm: {
        authorizationOrgId: "",
        authorizedOrgId: "",
      },
      authOrgsVisible: false,
      authOrg: {},
      authType: 1,
      orgList: [],
      loading: false,
      regionName: "",
    };
  },
  methods: {
    areaClickAction(data) {
      this.regionName = data.name;
      this.newForm.reginId = data.id;
    },
    getRegionDetail(id) {
      this.$get("business/business/regionDetail", {
        id,
      })
        .then((res) => {
          if (res.code == 0) {
            this.regionName = res.data.name;
          } else {
            this.regionName = null;
          }
        })
        .catch((err) => {});
    },
    getData() {
      let url = this.isAdmin
        ? "/systemsetup/systemsetup/orgTreeList"
        : "/systemsetup/department/departmentTree";
      this.$get(url).then(
        (res) => {
          if (!this.isAdmin) {
            res.data.list.forEach((item) => {
              item.list = [];
            });
          }
          this.data = [res.data];
          // this.getRegionDetail(res.data.reginid);
        },
        (err) => {
          if (err.msg) {
            this.$message.error(err.msg);
          }
        }
      );
    },
    getAllName(node, names) {
      names.push(node.data.name);
      if (node.parent && node.data.pid != 0) {
        this.getAllName(node.parent, names);
      }
    },
    newOrg() {
      this.newModalTitle = "新建部门";
      this.newForm = {};
      this.regionName = null;
      this.newForm.pid = this.activeData.id;
      this.newModalVisible = true;
      if (this.$refs["newForm"]) {
        this.$refs["newForm"].resetFields();
      }
    },
    editOrg() {
      console.log(this.activeData.reginid);

      if (this.activeData.reginid) {
        this.getRegionDetail(this.activeData.reginid);
      }else{
        this.regionName = null;
      }
      this.newModalTitle = "编辑部门";
      this.newForm = {
        id: this.activeData.id,
        name: this.activeData.name,
        des: this.activeData.des,
      };
      this.newModalVisible = true;
    },
    deleteOrg() {
      this.showConfirm("确定删除该部门吗？", () => {
        this.deleting = true;
        let url = this.isAdmin
          ? "/systemsetup/systemsetup/orgDelete"
          : "/systemsetup/department/departmentDelete";
        this.$post(url, {
          id: this.activeData.id,
        }).then(
          (res) => {
            this.deleting = false;
            this.$message.success("删除成功");
            this.removeNode(this.activeNode, this.activeData);
          },
          (err) => {
            this.deleting = false;
            this.$message.error(err.msg);
          }
        );
      });
    },
    removeNode(node, data) {
      const parent = node.parent;
      const children =
        (this.isAdmin ? parent.data.orgs : parent.data.list) || parent.data;
      const index = children.findIndex((d) => d.id === data.id);
      children.splice(index, 1);
    },
    submitAction() {
      this.$refs["newForm"].validate((valid) => {
        if (valid) {
          this.adding = true;
          let params = Object.assign({}, this.newForm);
          let url = "";
          if (this.newForm.id) {
            url = this.isAdmin
              ? "/systemsetup/systemsetup/orgUpdate"
              : "/systemsetup/department/departmentUpdate";
          } else {
            url = this.isAdmin
              ? "/systemsetup/systemsetup/orgAdd"
              : "/systemsetup/department/departmentAdd";
          }
          if (!this.isAdmin) {
            delete params.pid;
          }
          this.$ajax({
            url: url,
            method: "post",
            data: params,
          }).then(
            (data) => {
              this.adding = false;
              this.$message({
                type: "success",
                message: "保存成功",
                center: true,
              });
              this.newModalVisible = false;
              this.getData();
            },
            (error) => {
              this.adding = false;
              this.$message.error(error.msg);
            }
          );
        } else {
          return false;
        }
      });
    },
    handleNodeClick(data, node, n) {
      this.activeNodeId = node.id;
      let orgNames = [data.name];
      // this.getAllName(node,orgNames)
      // orgNames = orgNames.reverse()
      this.$emit("nodeClick", data, node.level, orgNames);
    },
    showContextMenu(event, data, node, el) {
      if (!this.$store.getters.hasEditPermission) {
        return false;
      }
      if (this.isAdmin) {
        const menuList = [
          {
            name: "新建子部门",
            handler: "new",
            access: "",
          },
          {
            name: "编辑",
            handler: "edit",
            access: "",
          },
          {
            name: "删除",
            handler: "delete",
            access: "",
          },
          {
            name: "授权",
            handler: "auth",
            access: "006001008",
          },
          {
            name: "取消授权",
            handler: "cancelAuth",
            access: "006001009",
          },
        ];
        this.menuList = menuList.filter((item) => {
          if (
            this.hasPermission("006001008") &&
            !this.hasPermission("006001009")
          ) {
            return item.access !== "006001009";
          } else if (
            this.hasPermission("006001009") &&
            !this.hasPermission("006001008")
          ) {
            return item.access !== "006001008";
          } else if (
            !this.hasPermission("006001009") &&
            !this.hasPermission("006001008")
          ) {
            return item.access !== "006001008" && item.access !== "006001009";
          }
          return item;
        });
      } else {
        if (node.data.id == "0") {
          this.menuList = [
            {
              name: "新建子部门",
              handler: "new",
            },
          ];
        } else {
          this.menuList = [
            {
              name: "编辑",
              handler: "edit",
            },
            {
              name: "删除",
              handler: "delete",
            },
          ];
        }
      }
      if (!this.ContextMenu) this.menuVisible = false;
      else this.menuVisible = true;
      let nodeId = node.id;
      this.activeNode = node;
      this.activeData = node.data;
      this.menuX = event.clientX;
      this.menuY = event.clientY;
    },
    menuHandler(type) {
      this.menuVisible = false;
      if (type == "new") {
        this.newOrg();
      } else if (type == "edit") {
        this.editOrg();
      } else if (type == "delete") {
        this.deleteOrg();
      } else if (type == "auth") {
        this.showAuth();
      } else if (type == "cancelAuth") {
        this.showCancelAuth();
      }
    },
    hideMenu() {
      this.menuVisible = false;
      // this.activeNode = null
    },
    clickDom() {
      this.hideMenu();
    },
    showAuth() {
      this.authType = 1;
      this.authModalTitle = "授权";
      this.authForm = {};
      this.authForm.authorizationOrgId = this.activeData.id;
      this.authModalVisible = true;
      if (this.$refs["authForm"]) {
        this.$refs["authForm"].resetFields();
      }
    },
    showCancelAuth() {
      this.authType = 0;
      this.authModalTitle = "取消授权";
      this.authForm = {};
      this.authForm.authorizationOrgId = this.activeData.id;
      this.authModalVisible = true;
      if (this.$refs["authForm"]) {
        this.$refs["authForm"].resetFields();
      }
    },
    chooseOrg() {
      this.authOrgsVisible = true;
      if (this.orgList.length == 0) {
        this.getOrg();
      }
    },
    getOrg() {
      this.loading = true;
      this.$get("/systemsetup/systemsetup/getOrgAllList")
        .then((res) => {
          this.loading = false;
          this.orgList = res.data;
        })
        .catch((err) => {
          this.loading = false;
          this.$message.success(err.msg);
        });
    },
    selectOrg(item) {
      this.authOrgsVisible = false;
      this.authOrg = item;
      this.$set(this.authForm, "authorizedOrgId", item.id);
    },
    submitAuthAction() {
      this.$refs["authForm"].validate((valid) => {
        if (valid) {
          this.adding = true;
          let url = "/systemsetup/systemsetup/authorization";
          if (this.authType == 0) {
            url = "/systemsetup/systemsetup/cancelAuthorization";
          }
          this.$post(url, this.authForm)
            .then((res) => {
              this.adding = false;
              this.$message.success("操作成功");
              this.authModalVisible = false;
              this.authForm = {};
              this.authOrg = {};
            })
            .catch((err) => {
              this.adding = false;
              this.$message.success(err.msg);
            });
        }
      });
    },
  },
  created() {
    this.getData();
  },
  mounted() {
    document.addEventListener("click", this.clickDom, false);
  },
  destroyed() {
    document.removeEventListener("click", this.clickDom, false);
  },
};
</script>
